package com.ui.controller;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.wanmei.util.CookieUtil;
import com.wanmei.commons.JsonUtils;
import com.wanmei.pojo.CartItem;
import com.wanmei.pojo.Orderdetail;
import com.wanmei.pojo.OrderProduct;
import com.ui.service.ProductService;
import com.ui.service.OrderDetailService;
import com.ui.service.OrderProductService;


@Controller
@RequestMapping("/order")
public class WebUiOrderController {

    @Autowired
    private ProductService productService;
    @Autowired
    private OrderProductService orderProductService;
    @Autowired
    private OrderDetailService orderDetaildetailService;

    //生成订单
    @RequestMapping("/orderview")
    public String getOrderAdd(@RequestParam("pids") Integer[] pids, HttpServletRequest request,
                              HttpServletResponse response) {
        // 生成订单
        // productService
        //到cookie中取订单
        String cookie = CookieUtil.getCookieValue(request, "CART_ITEM", true);
        if (StringUtils.isBlank(cookie)) {
            return "productlist";
        }
        //将cookie中订单的集合转换成list
        List<CartItem> items = JsonUtils.jsonToList(cookie, CartItem.class);



        //获取订单需要支付的商品kuid
        List list = Arrays.asList(pids);

        List<CartItem> orders = items.stream().filter(a -> list.contains(a.getKuid())).collect(Collectors.toList());
        //int j=orderDetaildetailService.insert(orders.get())
        String orderKey = orderProductService.insert(orders);
        // 删除购物车
        CookieUtil.delCookie(request, response, "CART_ITEM");
        return "forward:/order/orderList?orderKey="+orderKey;
    }

    @RequestMapping("/orderList")
    public String showOrder(String orderKey,HttpServletRequest request) {
        // 查询订单信息，orderKey也就是oid
        List<Orderdetail> listDetail = orderDetaildetailService.selectByOid(orderKey);
        OrderProduct order = orderProductService.selectByOid(orderKey);

        request.setAttribute("detail", listDetail);
        request.setAttribute("order", order);
        return "order";
    }

    @RequestMapping("/payorder")
    public String payOrder(String oid,String sumPrice,HttpServletRequest request) {
        request.setAttribute("oid", oid);
        request.setAttribute("sumPrice", sumPrice);
        return "payresult";
    }

}
